package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZDepartment;
import com.sec.etech.employeesync.mapper.OrgEmployeeZDepartmentMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class DepartmentConfigHandler implements ConfigTableHandler<OrgEmployeeZDepartment> {

    @Resource
    private OrgEmployeeZDepartmentMapper departmentMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZDepartment department = getEntityByName(name);
        if (department == null) {
            department = new OrgEmployeeZDepartment();
            department.setCode(generateNextCode());
            department.setName(name);
            department.setActive(1);
            insertEntity(department);
            log.info("新增部门配置:name={}", name);
        }
        return department.getDepartmentId();
    }

    @Override
    public OrgEmployeeZDepartment getEntityByName(String name) {
        return departmentMapper.selectOne(Wrappers.<OrgEmployeeZDepartment>lambdaQuery()
                .eq(OrgEmployeeZDepartment::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZDepartment politics = departmentMapper.selectOne(Wrappers.<OrgEmployeeZDepartment>lambdaQuery()
                .orderByDesc(OrgEmployeeZDepartment::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZDepartment::getCode)
                .orElse("0");

        return generateNextSerialNumber(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZDepartment entity) {
        departmentMapper.insert(entity);
    }
}
